import type { Router } from 'vue-router'
import { treeToList } from '@/utils/tree-util'
import _ from 'lodash'
import { HomeConst, LoginConst, PAGE_PATH_404 } from '@/constants/system/router-const'
/**
 * 获取所有vue组件引用地址 用于构建路由
 * */
const modules = import.meta.glob('@/views/**/**.vue')

/**
 * @param {Router} router  路由
 * @returns {Router} 重置后的路由
 * @description 重置路由
 * @description Reset router
 */
export function resetRouter(router: Router): Router {
  const resetWhiteNameList = [LoginConst.LOGIN_PAGE_NAME, '_Home', HomeConst.HOME_PAGE_NAME, PAGE_PATH_404, '403', 'Account', 'HelpDoc', 'HelpDocDetail']
  router.getRoutes().forEach((route) => {
    const { name } = route
    if (name && !resetWhiteNameList.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
  return router
}

/**
 * 转换后端路由数据中的字段，如果后端路由数据字段和前端路由数据字段不一致，需要在这里进行转换
 * @param {Array} routers路由
 * @returns {AppRouteRecordRaw[]} 处理后的数据
 */
export function handleRouters(menuList: any[]) {
  return _(treeToList(menuList))
    .filter((e) => e.href || e.frameUrl)
    .filter((e) => e.menu_type !== 2)
    .map((item) => {
      return {
        parentId: item.pid,
        menuId: item.id,
        path: item.href,
        component: item.file_path,
        icon: item.icon,
        menuName: item.title,
        menuType: item.menu_type,
        visibleFlag: item.is_show === 1,
        disabledFlag: item.status === 2,
        sort: item.sort
        // frameFlag: false,
        // frameUrl: null,
        // cacheFlag: false,
        // permsType: 1,
        // webPerms: 'system:menu:batchDelete',
        // apiPerms: 'system:menu:batchDelete',
        // contextMenuId: 26,
      }
    })
    .value()
}

/**
 * @param {any[]} routers 路由
 * @returns {AppRouteRecordRaw[]} 处理后的路由
 * @description 处理后端路由数据
 */
export function buildRouter(routers: any[]): AppRouteRecordRaw[] {
  const list = handleRouters(routers)
  
  const routerList: AppRouteRecordRaw[] = []
  for (const item of list) {
    if (!item.menuId) continue
    if (!item.path) continue
    if (item.deletedFlag && item.deletedFlag === true) continue

    let route = {
      path: item.path.startsWith('/') ? item.path : `/${item.path}`,
      // 使用【menuId】作为name唯一标识
      name: item.menuId.toString(),
      meta: {
        // 父级id
        pid: item.parentId.toString(),
        // 数据库菜单(页面)id
        id: item.menuId.toString(),
        // 组件名称
        componentName: item.menuId.toString(),
        // 菜单展示
        title: item.menuName,
        // 菜单图标展示
        icon: item.icon,
        // 是否在菜单隐藏
        hideInMenu: !item.visibleFlag,
        // 页面是否keep-alive缓存
        keepAlive: item.cacheFlag,
        // 是否为外链
        frameFlag: item.frameFlag,
        // 外链地址
        frameUrl: item.frameUrl,
        // 是否 rename了组件的名字
        renameComponentFlag: false
      }
    }
    if (item.frameFlag) {
      route.component = () => import('@/components/framework/iframe/iframe-index.vue')
    } else {
      let componentPath = item.component && item.component.startsWith('/') ? item.component : '/' + item.component
      let relativePath = `/src/views${componentPath}`
      // // eslint-disable-next-line no-prototype-builtins
      route.component = modules[relativePath]
    }
    routerList.push(route)
  }
  return routerList
}
